package com.dbq.fast.util;

import android.util.LruCache;

import com.dbq.fast.App;

/**
 * Created by yh on 2017/11/14.
 * 处理 LruCache 和SharePreference
 */

public class Cache<T,K> {
    private LruCache<T,K>  lruCache;
    public Cache(){
        int cacheSize = SystemUtil.getMemoryCacheSize(App.getInstance());

        lruCache = new LruCache<T,K>(cacheSize){
            @Override
            protected int sizeOf(T key, K value) {

                if (value instanceof String){
                    return ((String)value).getBytes().length;
                }
                return super.sizeOf(key, value);
            }
        };
    }
    /**
     * @description 将bitmap添加到内存中去
     *
     * @param key
     * @param bitmap
     */
    public void addToMemoryCache(T key, K bitmap) {
        if (getStrFromMemCache(key) == null) {
            lruCache.put(key, bitmap);
        }
    }

    /**
     * @description 通过key来从内存缓存中获得bitmap对象
     *
     * @param key
     * @return
     */
    private K getStrFromMemCache(T key) {
        return lruCache.get(key);
    }

    private String getStrFromSPCache(String key){
        return SpUtil.getString(key);
    }

    private void addStrToSpCache(String key,String value){
        SpUtil.setString(key,value);
    }

    public K getCache(T key){
        if (getStrFromMemCache(key) != null){
                return getStrFromMemCache(key);
        }else if(getStrFromSPCache((String)key) != null){
            return (K)getStrFromSPCache((String)key);
        }
        return null;
    }
    public boolean saveCache(T key,K value){
        try {
            addToMemoryCache(key,value);
            if (key instanceof String && value instanceof String){
                addStrToSpCache((String)key,(String)value);
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }

}
